package com.photoeditor.demo.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.text.format.DateUtils;
import android.view.KeyEvent;

import com.common.base.utils.thread.ThreadPool;
import com.common.commercialize.utils.TaskRunnable;
import com.photoeditor.R;
import com.photoeditor.demo.app.ActionConstant;
import com.photoeditor.demo.app.XActivity;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.fragement.HomeFragment;
import com.photoeditor.demo.ui.widget.ScrollLimitViewPager;
import com.photoeditor.demo.util.update.UpdateUtil;

import java.lang.ref.WeakReference;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Photo Editor的主界面
 */
public class HomeActivity extends XActivity {

    public static final int PAGE_MAIN = 0;
    public static final int PAGE_CAMERA = 1;

    public static final String EXTRA_FROM_SPLASH = "EXTRA_FROM_SPLASH";
    public static final String EXTRA_FROM_RESTORE = "EXTRA_FROM_RESTORE";
    public static final String EXTRA_FROM_OUTSIDE = "EXTRA_FROM_OUTSIDE";
    public static final String EXTRA_GO_TO_HOME = "EXTRA_GO_TO_HOME";
    private static final int MESSAGE_DISMISS_SPLASH = 111;
    private static final long DELAY = 2000;

    @Bind(R.id.pager)
    ScrollLimitViewPager mPager;

    HomeFragment mEntranceFragment;
    private EntranceHandler mHandler = new EntranceHandler(HomeActivity.this);
    private PagerAdapter mPagerAdapter;

    private boolean mIsStartUpToHomePage = true;

    private int mSplashImgHeight = 0;

    private boolean mIsFromSplash = false;
    private boolean mIsFromOutside = false;

    private boolean mShowSplashAd;//展示了开屏广告
    private boolean mIntoMain;//跳转到了主页面
    private boolean mJump2Ad;
    private boolean mGo2Home;

    private Runnable mRunnableAfterAd = new AfterAdRunnable(HomeActivity.this);

    public static boolean shouldShowSVipGuideAnimation() {
        return false/*SPDataManager.isEnterMainPageBefore() &&
                !SVipPurchaseActivity.isEnterPageBefore() &&
                !SPDataManager.isShowGuideAnimation() &&
                !AppVipManager.isVip()*/;
    }

    public static void startMainClearTop4ReportActivity(Context context, String fromStatistic, int fun) {
        Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    public static void startMainClearTop(Context context) {
        Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    public static void back2Home(Activity activity) {
        Intent intent = new Intent(activity, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //主动跳到主页
        intent.putExtra(EXTRA_GO_TO_HOME, true);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
//        EventBus.getDefault().register(this);
        init(savedInstanceState);
        mShowSplashAd = false;
        mIntoMain = false;
        mJump2Ad = false;
        //GalleryActivity.startGallerySelectSwapImages(this);
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_RETENTION,
                StatisticsConstant.UMENG_CUSTOM_EVENT_ALL, StatisticsConstant.UMENG_CUSTOM_EVENT_OPEN);
        if (SpUtils.obtain().getBoolean("st_n_nh", true)) {
            SpUtils.obtain().save("st_n_nh", false);
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_NEW_HOME);
        }
        mGo2Home = getIntent().getBooleanExtra(EXTRA_GO_TO_HOME, false);
        if (mGo2Home) {
            swipeToHomePage();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mGo2Home = intent.getBooleanExtra(EXTRA_GO_TO_HOME, false);
        if (mGo2Home) {
            swipeToHomePage();
        }
    }

    private void init(Bundle savedInstanceState) {
        initData(savedInstanceState);
        initView();

//        showDialog();
    }

    private void showDialog() {
        if (mIsFromOutside) {
            return;
        }

        boolean shouldShowSVipGuideAnimation = shouldShowSVipGuideAnimation();
        if (shouldShowSVipGuideAnimation) {
            mIsCanShowRateDialog = false;
        }
        //3日限免弹窗
        boolean showFreeSVIPDialog = false;
//        if(!shouldShowSVipGuideAnimation && !SPDataManager.hasShowFreeSVIPOver24() && over24HoursFromLast() && !AppVipManager.isVip()) {
//            //距离上次进入超过24小时
//            showFreeSVIPDialog = true;
//            mIsCanShowRateDialog = false;
//            new LimitFreeSVipPurchaseDialog(this).show();
//            SPDataManager.setHasShowFreeSVIPOver24();
//        }
        SPDataManager.setLastTimeIntoMain(System.currentTimeMillis());
        //亮点功能引导
        /*if (!shouldShowSVipGuideAnimation && !showFreeSVIPDialog && over8HoursFromLastShow()) {
            if (!SPDataManager.hasUseGifSticker()) {
                //第二次进入展示gif贴纸引导视频
                if (SPDataManager.canShowGifSticker()) {
                    //gif下载下来再展示
                    PreloadManager preloadManager = PreloadManager.getInstance();
                    String url = preloadManager.getConfig(PreLoadConfig.CONFIG_GUIDE_GIF_STICKER_ID);
                    if (!TextUtils.isEmpty(url)) {
                        String preloadFile = preloadManager.getPreloadFile(url);
                        if (!TextUtils.isEmpty(preloadFile)) {
                            mGuideVideoDialog = new GuideDialog(this, R.string.guide_gif_sticker_title,
                                    R.string.guide_gif_sticker_content,
                                    R.string.try_it,
                                    preloadFile,
                                    new GuideDialog.GuideDialogListener() {
                                        @Override
                                        public void onButtonClick() {
                                            GalleryActivity.startGallerySelectImageToAddSticker(EntranceActivity.this,
                                                    InsideStickerTool.STICKER_PKG_NAME_GIF,
                                                    "hot");
                                        }
                                    });
                            mGuideVideoDialog.show();
                            SPDataManager.setHasUseGifSticker(true);
                            SPDataManager.setCanShowGifSticker(false);
                            SPDataManager.saveLastShowTimeMainGuide();
                            mIsCanShowRateDialog = false;
                        }
                    }
                }
                SPDataManager.setCanShowGifSticker(true);
            } else if (!SPDataManager.hasUseCollage()) {
                //下载下来再展示
                PreloadManager preloadManager = PreloadManager.getInstance();
                String url = preloadManager.getConfig(PreLoadConfig.CONFIG_GUIDE_COLLAGE_VIDEO_ID);
                if (!TextUtils.isEmpty(url)) {
                    String preloadFile = preloadManager.getPreloadFile(url);
                    if (!TextUtils.isEmpty(preloadFile)) {
                        mGuideVideoDialog = new GuideDialog(this, R.string.guide_collage_title,
                                R.string.guide_collage_content,
                                R.string.try_it,
                                preloadFile,
                                new GuideDialog.GuideDialogListener() {
                                    @Override
                                    public void onButtonClick() {
                                        GalleryActivity.startGallerySelectCollageImages(EntranceActivity.this, "");
                                    }
                                });
                        mGuideVideoDialog.show();
                        SPDataManager.setHasUseCollage(true);
                        SPDataManager.saveLastShowTimeMainGuide();
                        mIsCanShowRateDialog = false;
                        PreloadManager.getInstance().addIgnorePreloadUrl(url);
                    }
                }
            }
        }*/
        //判断是否当天首次登陆
        if (!DateUtils.isToday(SPDataManager.getFirstInTimeOfDay())) {
            // PE1.01版本修改规则：第二天启动，不论是否满足评分要求，直接显示评分引导
//            if (mIsCanShowRateDialog && isSecondDay(SPDataManager.getFirstInTimeOfDay())) {
//                RateGuide.showRate(this, true, null);
//            }
            SPDataManager.setFirstInTimeOfDay(System.currentTimeMillis());
            //清零
            SPDataManager.setOpenAppCountToday(1);
            SPDataManager.setTakePictureCount(0);
            SPDataManager.setEditCount(0);
            SPDataManager.setShareCountOfDay(0);
            SPDataManager.setDownloadCountToday(0);

//            SpUtils.obtain().save(SVipController.SP_KEY_COUNT_SHOW_SVIP_ACTIVITY_AUTO_TODAY, 0);
//            SVipController.getInstance().setHasShowSVipOfEditComplete(false);
        } else {
//            if (mIsCanShowRateDialog) {
//                RateGuide.showRate(this);
//            }
        }
        mIsCanShowRateDialog = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mShowSplashAd) {
            mJump2Ad = true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        SPDataManager.setArtistEnable(false);
        if (mShowSplashAd && !mIntoMain) {
            mIntoMain = true;
            mShowSplashAd = false;
//            if (mSplashLayout != null) {
//                mSplashLayout.setVisibility(View.GONE);
//            }
            showDialog();
            checkUpdate();
            onTranstitionAniStart();
        }
    }

//    private boolean over8HoursFromLastShow() {
//        long lastShow = SPDataManager.getLastShowTimeMainGuide();
//        return (System.currentTimeMillis() - lastShow) >= 28800000;//八小时 1000 * 60 * 60 * 8
//    }
//
//    /**
//     * 距离上次进入主页超过24小时
//     * @return
//     */
//    private boolean over24HoursFromLast() {
//        long lastShow = SPDataManager.getLastTimeIntoMain();
//        return (System.currentTimeMillis() - lastShow) >= 86400000;//24小时 1000 * 60 * 60 * 24
//    }
//
//    /**
//     * 是否第二天
//     *
//     * @param before
//     * @return
//     */
//    private boolean isSecondDay(long before) {
//        Time time = new Time();
//        time.set(before);
//
//        int thenYear = time.year;
//        int thenMonth = time.month;
//        int thenMonthDay = time.monthDay;
//
//        time.set(System.currentTimeMillis());
//        return (thenYear == time.year)
//                && (thenMonth == time.month)
//                && (thenMonthDay + 1 == time.monthDay);
//    }

    private void initView() {
//        List<Fragment> fragments = getSupportFragmentManager().getFragments();
//        if (fragments != null) {
//            for (Fragment fragment : fragments) {
//                if (fragment != null) {
//                    if (fragment instanceof HomeFragment) {
//                        mEntranceFragment = (HomeFragment) fragment;
//                        mEntranceFragment.setActivity(this);
//                    }
//                }
//            }
//        }

        if (mEntranceFragment == null) {
            mEntranceFragment = new HomeFragment();
//            mEntranceFragment.setActivity(this);
        }

        mEntranceFragment.onPageSelected();

        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setCanScroll(false);
        mPager.setCurrentItem(getStartPage());
//        mSplashLayout = findViewById(R.id.splash_layout);
//        mTextView1 = (LinearGradientTextView) findViewById(R.id.textview1);
//        mTextView2 = (LinearGradientTextView) findViewById(R.id.textview2);
//        mTextView1.setColor(0xfffc8548, 0xffff409c, 0x00474747);
//        mTextView2.setColor(0xfffc8548, 0xffff409c, 0x00474747);
//        FontUtil.setCustomFontBold(mTextView1, mTextView2);

        //onPreTranstition();
        //measureTextSize();
//        ViewTreeObserver viewTreeObserver = mTextView1.getViewTreeObserver();
//        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//                                                  @Override
//                                                  public boolean onPreDraw() {
//                                                      if (mTextView1 != null) {
//                                                          mTextView1.getViewTreeObserver().removeOnPreDrawListener(this);
//                                                          startTextAnimation();
//                                                      }
//                                                      return false;
//                                                  }
//                                              });
        needShowSplashAd();
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SPLASH_LOADING);
    }

    private void needShowSplashAd() {
        //必须延迟执行，否则Fragment中ListView的Adapter还未初始化
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (SPDataManager.needShowSplashAd()) {
                    TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                        @Override
                        public void run() {
                            if (!mIntoMain) {
                                mIntoMain = true;
                                mShowSplashAd = false;
                                //已经没有SplashLayout了
                                //dismissFlashLayoutWithAnim();
                                showDialog();
                                checkUpdate();
                                onTranstitionAniStart();
                            }
                        }
                    };
                    if (!mShowSplashAd) {
                        taskRunnable.runSelfAdaptation();
                    } else {
                        //处理返回true却没有出现广告的情况
                        postDelayed(mRunnableAfterAd, 2000);
                    }
                } else {
                    //首次进入
                    SPDataManager.setNeedShowSplashAd();
                    mHandler.sendEmptyMessage(MESSAGE_DISMISS_SPLASH);
                }
            }
        }, 1000);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(EXTRA_FROM_RESTORE, true);
    }

//    private void measureTextSize() {
//        String string = mTextView2.getText().toString();
//        int width = DeviceUtils.getScreenWidthPx(this) - DeviceUtils.dip2px(this, 34);
//        float size = mTextView2.getTextSize();
//        int textMaxHeight = DeviceUtils.getScreenHeightPx(this) - mSplashImgHeight - DeviceUtils.dip2px(this, 10);
//        Paint paint = mTextView2.getPaint();
//        while (true) {
//            // 防止死循环
//            if (size > 500) {
//                break;
//            }
//            int measure = (int) paint.measureText(string);
//            if (measure >= width) {
//                size -= 1;
//                break;
//            }
//            int descent = (int) paint.descent();
//            int ascent = (int) paint.ascent();
//            int height = descent - ascent;
//            if (height > textMaxHeight) {
//                size -= 1;
//                break;
//            }
//            size += 1;
//            paint.setTextSize(size);
//        }
//        mTextView1.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
//        mTextView2.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextView1.getTextSize());
//    }

//    private void startTextAnimation() {
//        ThreadPool.runUITask(new Runnable() {
//            @Override
//            public void run() {
//                if (mTextView1 != null) {
//                    mTextView2.startColorAnimation(800, null);
//                    mTextView1.startColorAnimation(800, new AnimatorListenerAdapter() {
//                        @Override
//                        public void onAnimationEnd(Animator animation) {
//                            super.onAnimationEnd(animation);
//                            if(SPDataManager.needShowSplashAd()) {
//                                TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
//                                    @Override
//                                    public void run() {
//                                        if(!mIntoMain) {
//                                            mIntoMain = true;
//                                            mShowSplashAd = false;
//                                            dismissFlashLayoutWithAnim();
//                                            showDialog();
//                                            checkUpdate();
//                                            onTranstitionAniStart();
//                                        }
//                                    }
//                                };
//                                mShowSplashAd = SplashPageAdProvider.getInstance().showAd(taskRunnable, getString(R.string.app_name));
//                                if (!mShowSplashAd) {
//                                    taskRunnable.runSelfAdaptation();
//                                } else {
//                                    //处理返回true却没有出现广告的情况
//                                    postDelayed(mRunnableAfterAd, 2000);
//                                }
//                            } else {
//                                //首次进入
//                                SPDataManager.setNeedShowSplashAd();
//                                mHandler.sendEmptyMessage(MESSAGE_DISMISS_SPLASH);
//                            }
//                            /*if (mTextView1 != null) {
//                                mTextView1.animate().alpha(0).setDuration(320).setListener(new AnimatorListenerAdapter() {
//                                    @Override
//                                    public void onAnimationEnd(Animator animation) {
//                                        super.onAnimationEnd(animation);
//
//                                    }
//                                }).start();
//                                mTextView2.animate().alpha(0).setDuration(320).start();
//                            }*/
//                        }
//                    });
//                }
//            }
//        }, 820);
//    }

    private int getStartPage() {
        int defaultPage = mIsStartUpToHomePage && !isCaptureMode()
                ? PAGE_MAIN : PAGE_CAMERA;
        int extraPage = getIntent().getIntExtra(ActionConstant.Extras.EXTRA_PAGE, defaultPage);
        if (extraPage != PAGE_MAIN && extraPage != PAGE_CAMERA) {
            return defaultPage;
        } else {
            return extraPage;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        return super.onKeyDown(keyCode, event);
    }

//    private boolean isCameraPage() {
//        return mPager.getCurrentItem() == PAGE_CAMERA;
//    }

    public void swipeToHomePage() {
        if (mPager.getCurrentItem() == PAGE_MAIN) {
            return;
        }
        mPager.setCurrentItem(PAGE_MAIN);
    }

    //    public void swipeToCameraPage() {
//        mPager.setCurrentItem(PAGE_CAMERA);
//    }
//
    private boolean isCaptureMode() {
        String action = getIntent().getAction();
        if (MediaStore.ACTION_IMAGE_CAPTURE.equals(action) ||
                MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(action) ||
                MediaStore.ACTION_VIDEO_CAPTURE.equals(action) ||
                MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(action) ||
                ActionConstant.Actions.ACTION_CAPTURE_TO_EDIT_AND_PUBLISH.equals(action) ||
                ActionConstant.Actions.ACTION_IMAGE_CAPTURE_AND_SHARE.equals(action) ||
                ActionConstant.Actions.ACTION_MOTION_CAPTURE_AND_SHARE.equals(action)) {
            return true;
        }
        return false;
    }

    private void initData(Bundle savedInstanceState) {
        Intent i = getIntent();
        if (i != null) {
            boolean formRestore = false;
            if (savedInstanceState != null) {
                formRestore = savedInstanceState.getBoolean(EXTRA_FROM_RESTORE, false);
            }
            //不再需要转入动画
            if (!formRestore) {
                mIsFromSplash = i.getBooleanExtra(EXTRA_FROM_SPLASH, false);
            }
            mIsFromOutside = i.getBooleanExtra(EXTRA_FROM_OUTSIDE, false);
        }
    }

    @Override
    public void onBackPressed() {
        /*if (GiftBox.isShowing()) {
            GiftBox.closeGiftBox(this);
            return;
        }*/
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeCallbacks(mRunnableAfterAd);
        ButterKnife.unbind(this);
        mHandler.removeMessages(MESSAGE_DISMISS_SPLASH);
        mHandler.removeCallbacks(null);
        /*if (mSplashAnimator != null && mSplashAnimator.isRunning()) {
            mSplashAnimator.cancel();
        }*/
//        EventBus.getDefault().unregister(this);

    }

    private void startTranstition() {
        //不再需要SplashActivity，注释掉
        //dismissFlashLayoutWithAnim();
        onTranstitionAniStart();

    }

//    private void dismissFlashLayoutWithAnim() {
//        if (mSplashLayout != null) {
//            mSplashLayout.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    super.onAnimationEnd(animation);
//                    if (mSplashLayout != null) {
//                        mSplashLayout.setVisibility(View.GONE);
//                    }
//                }
//            }).setDuration(400).start();
//        }
//    }

    private void onTranstitionAniStart() {

    }

    /*private void onPreTranstition() {
        mBannerView = (ImageView) findViewById(R.id.banner_img);

        RelativeLayout.LayoutParams bannerLp = (RelativeLayout.LayoutParams) mBannerView.getLayoutParams();
        int dstbannerWidth = DeviceUtils.getScreenWidthPx(getApplicationContext());
        int dstbannerHeight = dstbannerWidth * 419 / 360;
        bannerLp.width = dstbannerWidth;
        bannerLp.height = dstbannerHeight;
        mSplashImgHeight = dstbannerHeight;
        initSplashImg();
    }

    private void initSplashImg() {
        StoreOnlineBean bannerBean = HomeOnlineManager.getInstance().getBannerBean();
        if (bannerBean != null && bannerBean.getChildModules() != null && bannerBean.getChildModules().size() > 0) {
            StoreOnlineBean bean = bannerBean.getChildModules().get(0);
            if (bean.getChildModules() != null && bean.getChildModules().size() > 0) {
                String[] urls = bean.getChildModules().get(0).getPreview().split("#");
                ImageLoader.loadImage(this, urls[0], 0, mBannerView, true);
            }
        }
    }*/

    private void checkUpdate() {
        if (mUpdateUtil == null) {
            mUpdateUtil = new UpdateUtil(this);
        }
        if (!mUpdateUtil.isUpdateDialogShowing()) {
            mUpdateUtil.checkUpdate();
        }
    }

    private static class AfterAdRunnable implements Runnable {
        private final WeakReference<HomeActivity> mSplashActivityRef;

        private AfterAdRunnable(HomeActivity mSplashActivityRef) {
            this.mSplashActivityRef = new WeakReference<>(mSplashActivityRef);
        }

        @Override
        public void run() {
            HomeActivity activity = mSplashActivityRef.get();
            if (activity != null) {
                if (!activity.mIntoMain && !activity.mJump2Ad) {
                    activity.mIntoMain = true;
//                    if (activity.mSplashLayout != null) {
//                        activity.mSplashLayout.setVisibility(View.GONE);
//                    }
                    activity.showDialog();
                    activity.checkUpdate();
                    activity.onTranstitionAniStart();
                }
            }
        }
    }

    private static class EntranceHandler extends Handler {
        private final WeakReference<HomeActivity> mSplashActivityRef;

        private EntranceHandler(HomeActivity mSplashActivityRef) {
            this.mSplashActivityRef = new WeakReference<>(mSplashActivityRef);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HomeActivity activity = mSplashActivityRef.get();
            if (activity != null && msg.what == MESSAGE_DISMISS_SPLASH) {
                activity.startTranstition();
                activity.showDialog();
                activity.checkUpdate();
            }
        }
    }

    public class ScreenSlidePagerAdapter extends FragmentPagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == PAGE_MAIN) {
                return mEntranceFragment;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 1;
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onDrawerLayoutEvent(DrawerLayoutEvent event) {
//
//    }
//
//
//    public ScrollLimitViewPager getViewPager() {
//        return mPager;
//    }

}
